package md.NJavaBase;

import android.util.Log;

import java.util.Timer;
import java.util.TimerTask;

enum NativeAdState
{
    Idle,//休闲
    Loading,//加载中
    Ready,//就绪
}

//原生广告管理器
public class NativeAdMgr {
    String Tag;
    public NativeAdMgr(String tag,String posID,INativeAdPlugin plugin)
    {
        Log.i(Tag,"Init");
        mPosID = posID;
        Tag = tag;
        mPlugin = plugin;
    }

    //delay 延迟加载时间，毫秒
    public void StartLoad(final int delay)
    {
        mD = 0;
        MainLoop.StartLoop(
                new ILoop() {
                    @Override
                    public boolean Do() {
                        if(mD++<delay) return true;

                        StartLoad();
                        return true;
                    }
                }
        );
    }


    //原生广告显示时被调用，用于统计曝光
    public void NotifyShow(){
        Log.i(Tag,"NotifyShow");
        mPlugin.NotifyShow();}

    //按钮被点击，用于统计点击次数
    public void NotifyBtnClick(){
        Log.i(Tag,"NotifyBtnClick");
        mPlugin.NotifyBtnClick();}

    //通知关闭
    public void NotifyClose(){
        Log.i(Tag,"NotifyClose");
        mPlugin.NotifyClose();
        mState = NativeAdState.Idle;
    }

    //获取图标的Url地址，无图标返回 ""
    public  String GetIconUrl(){return mPlugin.GetIconUrl();}

    //获取大图的Url地址，无大图返回 ""
    public  String GetImgUrl(){return mPlugin.GetImgUrl();}


    //"广告" 标签图片，无则返回 ""
    public  String GetLogUrl(){return mPlugin.GetLogUrl();}

    //标题文本 ，无则返回 ""
    public   String GetTitle(){return mPlugin.GetTitle();}

    //描述文本，无则返回 ""
    public String GetDesc(){return mPlugin.GetDesc();}

    //点击按钮文本,无则返回 ""
    public String GetClickBtnText(){return mPlugin.GetClickBtnText();}


    public boolean IsReady()
    {
        return mState ==  NativeAdState.Ready;
    }

    //开始加载
    void StartLoad()
    {
        mLostInterval++;
        if(mLostInterval<mIntervalLimit) return;
        mLostInterval = 0;

        if(
            mState!= NativeAdState.Idle|| //当前状态不是休闲
            !mPlugin.isInitialized()//尚未初始化
        ) return;

        //初始化成功后，加载间隔变成6秒
        mIntervalLimit = 6;

        Log.i(Tag,"StartLoad");
        mState = NativeAdState.Loading;
        mPlugin.Load(
                mPosID,
                new INativeAdCallback() {
                    @Override
                    public void onLoadSuccess() {
                        mState = NativeAdState.Ready;
                    }

                    @Override
                    public void onLoadFail() {
                        mState = NativeAdState.Idle;
                    }
                }
        );
    }

    INativeAdPlugin mPlugin;
    NativeAdState mState = NativeAdState.Idle;
    String mPosID;
    int mIntervalLimit = 1;
    int mLostInterval = 0;
    int mD=0;
}
